package cn.wit.summit.chwan.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.Stat.AdPosition;
import cn.wit.summit.chwan.Stat.StatFactory;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dbmanager.DownloadTaskManager;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.dto.PersonHomeData;
import cn.wit.summit.chwan.models.dto.PersonHomeDataUrl;
import cn.wit.summit.chwan.models.dto.SurplusNumberBean;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.activity.ChangePwdActivity;
import cn.wit.summit.chwan.ui.activity.MYFollowGamsActivity;
import cn.wit.summit.chwan.ui.activity.MainActivity;
import cn.wit.summit.chwan.ui.activity.MainLoginActivity;
import cn.wit.summit.chwan.ui.activity.NoticeActivity;
import cn.wit.summit.chwan.ui.activity.SettingActivity;
import cn.wit.summit.chwan.ui.activity.UpdateActivity;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.utils.APKUtils;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.DateUtils;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.RedEnvelopeUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.widgets.MyBadgeView;
import q.rorbin.badgeview.Badge;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/4/11.
 */

public class PersonalFragment extends Fragment {
    private String TAG = "PersonalFragment";

    @Bind(R.id.ennergytext)
    TextView ennergytext;
    @Bind(R.id.userIcon)
    SimpleDraweeView userIcon;
    @Bind(R.id.appName)
    TextView appName;
    @Bind(R.id.moneyText)
    TextView moneyText;
    @Bind(R.id.ennegerNumber)
    TextView ennegerNumber;
    @Bind(R.id.toCash)
    TextView toCash;
    @Bind(R.id.setting)
    ImageView setting;
    @Bind(R.id.messageImg)
    ImageView messageImg;
    @Bind(R.id.updateImg)
    ImageView updateImg;
    @Bind(R.id.updateLayout)
    RelativeLayout updateLayout;
    @Bind(R.id.followLayout)
    RelativeLayout followLayout;
    @Bind(R.id.toLogin)
    TextView toLogin;
    @Bind(R.id.bannerAd)
    SimpleDraweeView bannerAd;
    @Bind(R.id.htmltest)
    Button htmltest;
    Context context;
    Badge updateImgBadge;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;
    private Retrofit retrofitLogin;
    private ApiUtil apiLogin;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.my_user_center_fragment, container, false);
        ButterKnife.bind(this, view);

        retrofitManager = RetrofitManager.getInstance(getActivity());
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);
        retrofitLogin = retrofitManager.getLoginRetrofit();
        apiLogin = retrofitLogin.create(ApiUtil.class);

        context = getContext();
//        if (RpcConstant.isDebug) {
//            htmltest.setVisibility(View.VISIBLE);
//        }
        getUpdateInfo();
        updateMessage();

        long ennerTime = PreferenceUtil.getLongPreferences(context, "clickTodayGetEnergy");
        if (ennerTime == 0 || !DateUtils.isToday(ennerTime)) {
            energybadge = new MyBadgeView(getContext())
                    .bindTarget(ennergytext)
                    .setBadgeNumber(-1)

                    .setBadgePadding(getResources().getDimensionPixelSize(R.dimen.wdp8), false)

                    .setBadgeBackground(getResources().getDrawable(R.mipmap.notice_round))
                    .setBadgeTextSize(getResources().getDimensionPixelSize(R.dimen.wdp18), false)
                    .setBadgeGravity(Gravity.START | Gravity.TOP)
                    .setBadgeTextColor(Color.WHITE)
                    .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
                        @Override
                        public void onDragStateChanged(int dragState, Badge badge, View targetView) {
                            if (dragState == 4)
                                badge.hide(false);
                        }
                    });

        }
        updateImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (updateImgBadge != null) {
                    updateImgBadge.hide(false);
                }
                Intent intent = new Intent(context, UpdateActivity.class);
                startActivity(intent);
            }
        });
        htmltest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtil.getInstance().goShareWebActivity(context, "file:///android_asset/webtest.html");
            }
        });
        return view;
    }

    private void updateMessage() {
        MainActivity activity = (MainActivity) getActivity();

        if (activity.surplusNumberBean != null) {

            int showNumber = activity.surplusNumberBean.getNotice_surplus_number() + activity.surplusNumberBean.getReplay_surplus_number();
            if (showNumber > 0 || activity.surplusNumberBean.getPraise_surplus_number() > 0) {
                if (showNumber == 0) {
                    showNumber = -1;
                }
                messagebadge = new MyBadgeView(getContext())
                        .bindTarget(messageImg)
                        .setBadgeNumber(showNumber > 99 ? 99 : showNumber)

                        .setBadgePadding(getResources().getDimensionPixelSize(R.dimen.wdp8), false)

                        .setBadgeBackground(getResources().getDrawable(showNumber > 99 ? R.mipmap.notice_round_nore99 : R.mipmap.notice_round))
//                        .setBadgeBackgroundColor(Color.RED)
                        .setBadgeTextSize(getResources().getDimensionPixelSize(R.dimen.wdp18), false)
                        .setBadgeGravity(Gravity.END | Gravity.TOP)
                        .setBadgeTextColor(Color.WHITE)
                        .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
                            @Override
                            public void onDragStateChanged(int dragState, Badge badge, View targetView) {
                                if (dragState == 4)
                                    badge.hide(false);
                            }
                        });
            }
        }
    }

    private void getUpdateInfo() {
        if (NetWorkUtils.isNetworkConnected(context)) {
            try {
                final List<DownLoadTaskTable> downLoadTaskTables = DownloadTaskManager.getInstance().findAllGame();
                StringBuffer buffer = new StringBuffer();
                for (DownLoadTaskTable taskTable : downLoadTaskTables) {
                    buffer.append("," + taskTable.getPackageName());
                    APKUtils.APKInfo apkInfo = APKUtils.getInstance(context).getInstallAPKInfo(context, taskTable.getPackageName());
                    if (apkInfo == null) continue;
                    buffer.append("|");
                    buffer.append(apkInfo.getVersionName() + "_" + apkInfo.getVersionCode());
                }
                String packagenames = buffer.toString();
                packagenames = packagenames.replaceFirst(",", "");

                api.getAllGameVersion(packagenames).enqueue(new MyCallback<ResponseBase<List<GameListBaseBean>>>() {
                    @Override
                    public void onSuccess(ResponseBase<List<GameListBaseBean>> model) {
                        List<GameListBaseBean> data = model.getData_info();
                        if (data.size() > 0) {
                            Iterator<GameListBaseBean> gaIterator = data.iterator();
                            int needUpdateNumber = 0;
                            while (gaIterator.hasNext()) {
                                try {

                                    GameListBaseBean gameListBaseBean = gaIterator.next();
                                    APKUtils.APKInfo apkInfo = APKUtils.getInstance(context).getInstallAPKInfo(context, gameListBaseBean.getGame_package_name());
                                    if (apkInfo != null && apkInfo.getVersionCode() < gameListBaseBean.getGame_ver()) {
                                        DownLoadTaskTable taskTable = DownloadTaskManager.getInstance().findByGameId(gameListBaseBean.getGame_id());
                                        if (taskTable != null && taskTable.getNotUpdateVersion() == gameListBaseBean.getGame_ver()) {
                                            continue;
                                        }
                                        needUpdateNumber += 1;
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            if (needUpdateNumber > 0) {
                                if (updateImgBadge != null) {
                                    updateImgBadge.hide(false);
                                }
                                updateImgBadge = new MyBadgeView(getContext())
                                        .bindTarget(updateImg)
                                        .setBadgeNumber(needUpdateNumber > 99 ? 99 : needUpdateNumber)
                                        .setBadgePadding(getResources().getDimensionPixelSize(R.dimen.wdp8), false)
                                        .setBadgeBackground(getResources().getDrawable(needUpdateNumber > 99 ? R.mipmap.notice_round_nore99 : R.mipmap.notice_round))
                                        .setBadgeTextSize(getResources().getDimensionPixelSize(R.dimen.wdp18), false)
                                        .setBadgeGravity(Gravity.END | Gravity.TOP)
                                        .setBadgeTextColor(Color.WHITE)
                                        .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
                                            @Override
                                            public void onDragStateChanged(int dragState, Badge badge, View targetView) {
                                                if (dragState == 4)
                                                    badge.hide(false);
                                            }
                                        });
                            }
                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {

                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
        }
    }

    private void getPersonhomeData() {
        if (NetWorkUtils.isNetworkConnected(context)) {
            try {
                api.getPersonData("").enqueue(new MyCallback<ResponseBase<PersonHomeData>>() {
                    @Override
                    public void onSuccess(ResponseBase<PersonHomeData> model) {
                        final PersonHomeData data = model.getData_info();
                        if (data != null) {
                            if (data.getJump_ad_switch() == 1) {
                                bannerAd.setImageURI(data.getJump_cover_big_pic());
                                bannerAd.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        IntentUtil.getInstance().intentTo(getActivity(), data.getJump_info());
                                        StatFactory.getInstance().sendClickAdvertSpacePage(getContext(), AdPosition.getModeByEnum(8)
                                                , AdPosition.getNameByEnum(8), "", "", 1);
                                    }
                                });
                                bannerAd.setVisibility(View.VISIBLE);

                            } else {
                                bannerAd.setVisibility(View.GONE);
                            }
//                            if (data.getJump_game_count() > 0) {
//                                messagebadge = new QBadgeView(getContext())
//                                        .bindTarget(messageImg)
//                                        .setBadgeNumber(data.getJump_game_count())
//                                        .setBadgeBackgroundColor(Color.RED)
//                                        .setBadgeTextSize(getResources().getDimensionPixelSize(R.dimen.wdp20), false)
//                                        .setBadgeGravity(Gravity.END | Gravity.TOP)
//                                        .setBadgeTextColor(Color.WHITE)
//                                        .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
//                                            @Override
//                                            public void onDragStateChanged(int dragState, Badge badge, View targetView) {
//                                                if (dragState == 4)
//                                                    badge.hide(true);
//                                            }
//                                        });
//
//                            }

                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {

                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
        }
    }

    private void getUserinfo() {
        if (NetWorkUtils.isNetworkConnected(context)) {
            try {
                if (AccountUtil.getInstance().getUid() != 0) {
                    int uid = AccountUtil.getInstance().getUid();
                    String token = AccountUtil.getInstance().getToken();
                    apiLogin.checkToken(uid, token).enqueue(new MyCallback<ResponseBase<PersonHomeDataUrl>>() {
                        @Override
                        public void onSuccess(ResponseBase<PersonHomeDataUrl> model) {
                            PersonHomeDataUrl data = model.getData_info();
                            if (data != null) {
                                data.setToken(AccountUtil.getInstance().getToken());
                                AccountUtil.getInstance().saveAccountData(data);
                                initView();

                            }
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            if (code == 60001) {
                                AccountUtil.getInstance().accountLoginOut(getActivity());
                                initView();
                            } else {
                                ToastUtils.getInstance(context).showToastSystem(msg);
                            }
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
        }
    }


    Badge messagebadge;
    Badge energybadge;

    private void initView() {
        LogUtils.e(TAG + " initView()");
        AccountBean accountBean = AccountUtil.getInstance().getAccountData();
        if (accountBean == null || accountBean.getUid() == 0) {
            toLogin.setVisibility(View.VISIBLE);
            appName.setVisibility(View.GONE);
            userIcon.setImageURI("");
            ennegerNumber.setText("0");
            moneyText.setText("0");
        } else {
            toLogin.setVisibility(View.GONE);
            appName.setVisibility(View.VISIBLE);
            userIcon.setImageURI(Uri.parse(accountBean.getAvatar()));
            appName.setText(accountBean.getNickname());
            DecimalFormat df = new DecimalFormat("0.00");
            moneyText.setText("¥" + df.format(accountBean.getWallet() / 100f));
            ennegerNumber.setText(accountBean.getEnergies() + "");
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        initView();
//        getUpdateInfo();
        getPersonhomeData();
        getUserinfo();
        getNewRedEnvelope();
    }

    private void getNewRedEnvelope() {
        SharedPreferences s = MyApplication.getMyApplication().getRedps();
        if (s.getBoolean("isclose", false) == false) {
            Log.e("TAG", "PerOnResume");
            RedEnvelopeUtils.ShowRedEnvelope(getActivity());
        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
//            if (System.currentTimeMillis() - PreferenceUtil.getLastUpdateGamePreferences(context) > 24 * 60 * 60 * 1000) {
//                getUpdateInfov2();
//            } else {
            getPersonhomeData();
            getUserinfo();
            getNewRedEnvelope();
            getUpdateInfo();
            getSurplusNumber();
//            }

        }
    }

    private void getSurplusNumber() {
        if (NetWorkUtils.isNetworkConnected(getActivity())) {
            try {
                int uid = AccountUtil.getInstance().getUid();
                String token = AccountUtil.getInstance().getToken();
                api.getSurplusNumber(uid, token).enqueue(new MyCallback<ResponseBase<SurplusNumberBean>>() {
                    @Override
                    public void onSuccess(ResponseBase<SurplusNumberBean> model) {
                        SurplusNumberBean data = model.getData_info();
                        if (data != null) {
                            MainActivity activity = (MainActivity) getActivity();
                            activity.surplusNumberBean = data;
                            updateMessage();

                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @OnClick({R.id.toCash, R.id.secritMessage, R.id.ennergyLayout, R.id.backMessageImg, R.id.setting, R.id.updateLayout, R.id.updateImg, R.id.uploadImg, R.id.followLayout, R.id.messageLayout, R.id.titlelayout, R.id.toLogin, R.id.energyLayout, R.id.moneyLayout})
    void onclickx(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.toCash:
            case R.id.moneyLayout:
                if (AccountUtil.getInstance().getUidNotToLogin(context) == 0) return;
                IntentUtil.getInstance().goShareWebActivity(context, MyApplication.cfgPlug.getValue_wallet_url_v2());
                break;
            case R.id.secritMessage:
            case R.id.energyLayout:
                if (AccountUtil.getInstance().getUidNotToLogin(context) == 0) return;
                IntentUtil.getInstance().goShareWebActivity(context, MyApplication.cfgPlug.getValue_energy_secret_url());
                break;
            case R.id.ennergyLayout:
                if (AccountUtil.getInstance().getUidNotToLogin(context) == 0) return;
                if (energybadge != null)
                    energybadge.hide(false);
                PreferenceUtil.saveLongPreference(context, "clickTodayGetEnergy", System.currentTimeMillis());
                IntentUtil.getInstance().goShareWebActivity(context, MyApplication.cfgPlug.getValue_energy_receive_url());
                break;
            case R.id.backMessageImg:
                if (AccountUtil.getInstance().getUidNotToLogin(context) == 0) return;
                IntentUtil.getInstance().goShareWebActivity(context, MyApplication.cfgPlug.getValue_feedback_url_v3());
                break;
            case R.id.setting:
                if (MyApplication.accountBean == null) {
                    IntentUtil.getInstance().goLoginActivity(getActivity());
                } else {
                    if(MyApplication.accountBean.getToken()!=null){
                        startActivity(new Intent(getActivity(), SettingActivity.class));
                    }else{
                        ToastUtils.getInstance(getActivity()).showToastSystem("token为空");
                    }


                }

                break;
            case R.id.updateLayout:
                if (updateImgBadge != null) {
                    updateImgBadge.hide(false);
                }
                intent = new Intent(this.getContext(), UpdateActivity.class);
                startActivity(intent);
                break;
            case R.id.followLayout:
                if (AccountUtil.getInstance().getUidNotToLogin(context) == 0) return;
                intent = new Intent(this.getContext(), MYFollowGamsActivity.class);
                startActivity(intent);
                break;
            case R.id.messageLayout:
                if (AccountUtil.getInstance().getUidNotToLogin(context) == 0) return;
                if (messagebadge != null)
                    messagebadge.hide(false);
                intent = new Intent(this.getContext(), NoticeActivity.class);
                MainActivity activity = (MainActivity) getActivity();
                if (activity.surplusNumberBean != null) {
                    SurplusNumberBean bean = new SurplusNumberBean();
                    bean.setNotice_surplus_number(activity.surplusNumberBean.getNotice_surplus_number());
                    bean.setPraise_surplus_number(activity.surplusNumberBean.getPraise_surplus_number());
                    bean.setReplay_surplus_number(activity.surplusNumberBean.getReplay_surplus_number());
                    intent.putExtra("numberData", bean);
                    if (activity.surplusNumberBean.getNotice_surplus_number() > 0) {
                        activity.surplusNumberBean.setNotice_surplus_number(0);
                    } else {
                        activity.surplusNumberBean.setReplay_surplus_number(0);
                    }
                }
                startActivity(intent);
                break;
            case R.id.titlelayout:
                break;
            case R.id.toLogin:
                IntentUtil.getInstance().goLoginActivity(getActivity());
                break;
            case R.id.uploadImg:
                if (AccountUtil.getInstance().getUidNotToLogin(context) == 0) return;
                IntentUtil.getInstance().goShareWebActivity(context, MyApplication.cfgPlug.getValue_game_upload_url_v3());
                break;
        }
    }
}
